<template>
  <div class="doctor-prescription">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <h2>处方管理</h2>
          <div class="header-actions">
            <el-button type="primary" @click="showCreatePrescription">
              <el-icon><Plus /></el-icon> 新建处方
            </el-button>
            <el-button @click="refreshData">
              <el-icon><Refresh /></el-icon> 刷新数据
            </el-button>
          </div>
        </div>
      </template>
      
      <!-- 搜索和筛选区域 -->
      <div class="filter-container">
        <el-form :inline="true" :model="searchForm" ref="searchFormRef">
          <el-form-item label="患者姓名">
            <el-input v-model="searchForm.patientName" placeholder="请输入患者姓名" clearable />
          </el-form-item>
          <el-form-item label="处方状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
              <el-option label="待审核" value="待审核" />
              <el-option label="已审核" value="已审核" />
              <el-option label="已发药" value="已发药" />
              <el-option label="已作废" value="已作废" />
            </el-select>
          </el-form-item>
          <el-form-item label="日期范围">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
              style="width: 300px"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 处方列表 -->
      <el-table
        v-loading="loading"
        :data="prescriptionsList"
        style="width: 100%"
        border
        stripe
        row-key="id"
        :header-cell-style="{background:'#f5f7fa', color:'#606266', fontWeight: 'bold'}"
      >
        <el-table-column label="处方编号" prop="prescriptionId" min-width="120" align="center">
          <template #default="scope">
            {{ scope.row.prescriptionId || scope.row.id || scope.row._id || '--' }}
          </template>
        </el-table-column>
        <el-table-column label="患者姓名" prop="patientName" min-width="120" align="center">
          <template #default="scope">
            {{ scope.row.patientName || scope.row.patient?.name || '--' }}
          </template>
        </el-table-column>
        <el-table-column label="创建日期" prop="createTime" min-width="130" align="center">
          <template #default="scope">
            {{ formatDate(scope.row.createTime || scope.row.createdAt) || '--' }}
          </template>
        </el-table-column>
        <el-table-column label="诊断" prop="diagnosis" min-width="150" align="center" show-overflow-tooltip>
          <template #default="scope">
            <span v-if="Array.isArray(scope.row.diagnosis)">
              {{ scope.row.diagnosis.join('、') }}
            </span>
            <span v-else>{{ scope.row.diagnosis || '--' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="药品数量" prop="itemCount" min-width="100" align="center">
          <template #default="scope">
            {{ scope.row.items?.length || 0 }} 种
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="status" min-width="100" align="center">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ scope.row.status || '未知' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" min-width="200" align="center">
          <template #default="scope">
            <div class="action-buttons">
              <el-button size="small" type="primary" @click="viewPrescription(scope.row)" plain>
                <el-icon><View /></el-icon> 查看
              </el-button>
              <el-button 
                size="small" 
                type="warning" 
                @click="editPrescription(scope.row)" 
                plain
                :disabled="scope.row.status !== '待审核'"
              >
                <el-icon><Edit /></el-icon> 编辑
              </el-button>
              <el-button 
                size="small" 
                type="success" 
                @click="auditPrescription(scope.row)" 
                plain
                :disabled="scope.row.status !== '待审核'"
              >
                <el-icon><Check /></el-icon> 审核
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页控件 -->
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 新建/编辑处方对话框 -->
    <el-dialog
      v-model="prescriptionDialogVisible"
      :title="dialogTitle"
      width="1000px"
      destroy-on-close
      :close-on-click-modal="false"
    >
      <el-form
        ref="prescriptionFormRef"
        :model="prescriptionForm"
        :rules="prescriptionRules"
        label-width="100px"
        @submit.prevent
      >
        <!-- 基本信息 -->
        <div class="form-section">
          <h4 class="section-title">基本信息</h4>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="患者" prop="patientId">
                <el-select 
                  v-model="prescriptionForm.patientId" 
                  placeholder="请选择患者" 
                  filterable
                  remote
                  :remote-method="searchPatients"
                  :loading="patientLoading"
                  style="width: 100%"
                  @change="handlePatientChange"
                >
                  <el-option 
                    v-for="patient in patientOptions" 
                    :key="patient.id"
                    :label="patient.name"
                    :value="patient.id"
                  >
                    <div class="patient-option">
                      <span>{{ patient.name }}</span>
                      <span class="patient-info">({{ patient.gender }}, {{ patient.age }}岁)</span>
                    </div>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="医疗记录" prop="medicalRecordId">
                <el-select 
                  v-model="prescriptionForm.medicalRecordId" 
                  placeholder="请选择医疗记录" 
                  style="width: 100%"
                  :disabled="!prescriptionForm.patientId"
                >
                  <el-option 
                    v-for="record in medicalRecordOptions" 
                    :key="record.id"
                    :label="`${formatDate(record.visitDate)} - ${record.diagnosis || '无诊断'}`"
                    :value="record.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="处方类型" prop="type">
                <el-select v-model="prescriptionForm.type" placeholder="请选择类型" style="width: 100%">
                  <el-option label="西药处方" value="western" />
                  <el-option label="中药处方" value="chinese" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        
        <!-- 诊断信息 -->
        <div class="form-section">
          <h4 class="section-title">诊断信息</h4>
          <el-form-item label="诊断结果" prop="diagnosisText">
            <el-input
              v-model="prescriptionForm.diagnosisText"
              type="textarea"
              :rows="2"
              placeholder="请输入诊断结果，多个诊断用分号分隔"
              @blur="updateDiagnosisList"
            />
          </el-form-item>
          <div v-if="prescriptionForm.diagnosis.length > 0" class="diagnosis-tags">
            <el-tag
              v-for="(diag, index) in prescriptionForm.diagnosis"
              :key="index"
              closable
              @close="removeDiagnosis(index)"
              class="diagnosis-tag"
            >
              {{ diag }}
            </el-tag>
          </div>
        </div>
        
        <!-- 药品信息 -->
        <div class="form-section">
          <h4 class="section-title">
            药品信息
            <el-button type="primary" size="small" @click="addMedication" style="margin-left: 10px;">
              <el-icon><Plus /></el-icon> 添加药品
            </el-button>
          </h4>
          <el-table :data="prescriptionForm.items" style="width: 100%" border>
            <el-table-column label="操作" width="80">
              <template #default="scope">
                <el-button 
                  type="danger" 
                  size="small" 
                  circle
                  @click="removeMedication(scope.$index)"
                  :disabled="prescriptionForm.items.length <= 1"
                >
                  <el-icon><Delete /></el-icon>
                </el-button>
              </template>
            </el-table-column>
            <el-table-column label="药品名称" min-width="180">
              <template #default="scope">
                <el-select 
                  v-model="scope.row.drugId" 
                  filterable 
                  remote 
                  reserve-keyword
                  placeholder="请搜索药品" 
                  :remote-method="searchDrugs"
                  :loading="drugLoading"
                  style="width: 100%"
                  @change="(val) => handleDrugChange(val, scope.$index)"
                >
                  <el-option 
                    v-for="drug in drugOptions" 
                    :key="drug.id" 
                    :label="drug.name"
                    :value="drug.id"
                  >
                    <div class="drug-option">
                      <span>{{ drug.name }}</span>
                      <span class="drug-spec">{{ drug.specification }}</span>
                    </div>
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="规格" width="120">
              <template #default="scope">
                <span>{{ scope.row.specification || '--' }}</span>
              </template>
            </el-table-column>
            <el-table-column label="剂量" width="100">
              <template #default="scope">
                <el-input v-model="scope.row.dosage" placeholder="如：0.5g" />
              </template>
            </el-table-column>
            <el-table-column label="频次" width="120">
              <template #default="scope">
                <el-select v-model="scope.row.frequency" placeholder="选择频次">
                  <el-option label="每日一次" value="每日一次" />
                  <el-option label="每日两次" value="每日两次" />
                  <el-option label="每日三次" value="每日三次" />
                  <el-option label="每日四次" value="每日四次" />
                  <el-option label="每周一次" value="每周一次" />
                  <el-option label="按需服用" value="按需服用" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="数量" width="80">
              <template #default="scope">
                <el-input-number 
                  v-model="scope.row.quantity" 
                  :min="1" 
                  :max="999" 
                  size="small"
                />
              </template>
            </el-table-column>
            <el-table-column label="天数" width="80">
              <template #default="scope">
                <el-input-number 
                  v-model="scope.row.days" 
                  :min="1" 
                  :max="90" 
                  size="small"
                />
              </template>
            </el-table-column>
            <el-table-column label="用法说明" min-width="120">
              <template #default="scope">
                <el-input 
                  v-model="scope.row.instructions" 
                  placeholder="如：饭后服用"
                />
              </template>
            </el-table-column>
          </el-table>
        </div>
        
        <!-- 备注信息 -->
        <div class="form-section">
          <h4 class="section-title">备注信息</h4>
          <el-form-item label="处方备注">
            <el-input
              v-model="prescriptionForm.remarks"
              type="textarea"
              :rows="3"
              placeholder="处方的整体说明或注意事项"
            />
          </el-form-item>
        </div>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="prescriptionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitPrescription" :loading="prescriptionLoading">
            {{ isEdit ? '更新处方' : '保存处方' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 处方详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="处方详情"
      width="900px"
      destroy-on-close
    >
      <div v-loading="detailLoading">
        <div v-if="currentPrescription">
          <!-- 基本信息 -->
          <el-card class="detail-card" shadow="never">
            <template #header>
              <h4>基本信息</h4>
            </template>
            <el-descriptions :column="2" border>
              <el-descriptions-item label="处方编号">
                {{ currentPrescription.prescriptionId || currentPrescription.id }}
              </el-descriptions-item>
              <el-descriptions-item label="患者姓名">
                {{ currentPrescription.patientName || currentPrescription.patient?.name }}
              </el-descriptions-item>
              <el-descriptions-item label="开具时间">
                {{ formatDate(currentPrescription.createTime || currentPrescription.createdAt) }}
              </el-descriptions-item>
              <el-descriptions-item label="处方状态">
                <el-tag :type="getStatusType(currentPrescription.status)">
                  {{ currentPrescription.status }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="处方类型">
                {{ currentPrescription.type === 'western' ? '西药处方' : '中药处方' }}
              </el-descriptions-item>
              <el-descriptions-item label="开具医生">
                {{ currentPrescription.doctorName || '未知医生' }}
              </el-descriptions-item>
            </el-descriptions>
          </el-card>
          
          <!-- 诊断信息 -->
          <el-card class="detail-card" shadow="never" style="margin-top: 20px;">
            <template #header>
              <h4>诊断信息</h4>
            </template>
            <div v-if="currentPrescription.diagnosis && currentPrescription.diagnosis.length > 0">
              <el-tag
                v-for="(diag, index) in currentPrescription.diagnosis"
                :key="index"
                class="diagnosis-tag"
                type="info"
              >
                {{ diag }}
              </el-tag>
            </div>
            <div v-else>暂无诊断信息</div>
          </el-card>
          
          <!-- 药品清单 -->
          <el-card class="detail-card" shadow="never" style="margin-top: 20px;">
            <template #header>
              <h4>药品清单</h4>
            </template>
            <el-table :data="currentPrescription.items || []" style="width: 100%" border>
              <el-table-column label="序号" type="index" width="60" />
              <el-table-column label="药品名称" prop="drugName" min-width="150" />
              <el-table-column label="规格" prop="specification" width="120" />
              <el-table-column label="剂量" prop="dosage" width="100" />
              <el-table-column label="频次" prop="frequency" width="120" />
              <el-table-column label="数量" prop="quantity" width="80" />
              <el-table-column label="天数" prop="days" width="80" />
              <el-table-column label="用法说明" prop="instructions" min-width="120" />
            </el-table>
          </el-card>
          
          <!-- 备注信息 -->
          <el-card class="detail-card" shadow="never" style="margin-top: 20px;" v-if="currentPrescription.remarks">
            <template #header>
              <h4>备注信息</h4>
            </template>
            <p>{{ currentPrescription.remarks }}</p>
          </el-card>
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="printPrescription">
            <el-icon><Printer /></el-icon> 打印处方
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { prescriptionAPI, patientAPI, medicalRecordAPI, drugAPI, doctorAPI } from '@/utils/api'
import { formatDate } from '@/utils/date'
import { useUserStore } from '@/stores/user'
import { 
  Plus, Refresh, View, Edit, Check, Delete, Printer
} from '@element-plus/icons-vue'

// 路由实例
const router = useRouter()
const userStore = useUserStore()

// 数据加载状态
const loading = ref(false)
const prescriptionLoading = ref(false)
const detailLoading = ref(false)
const patientLoading = ref(false)
const drugLoading = ref(false)

// 表格数据
const prescriptionsList = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 对话框状态
const prescriptionDialogVisible = ref(false)
const detailDialogVisible = ref(false)

// 表单引用
const searchFormRef = ref(null)
const prescriptionFormRef = ref(null)

// 搜索表单
const searchForm = reactive({
  patientName: '',
  status: '',
  startDate: '',
  endDate: ''
})

// 日期范围
const dateRange = ref([])

// 处方表单
const prescriptionForm = reactive({
  patientId: '',
  medicalRecordId: '',
  type: 'western',
  diagnosisText: '',
  diagnosis: [],
  items: [
    { drugId: '', drugName: '', specification: '', dosage: '', quantity: 1, frequency: '', days: 1, instructions: '' }
  ],
  remarks: ''
})

// 表单验证规则
const prescriptionRules = {
  patientId: [{ required: true, message: '请选择患者', trigger: 'change' }],
  type: [{ required: true, message: '请选择处方类型', trigger: 'change' }],
  diagnosisText: [{ required: true, message: '请输入诊断结果', trigger: 'blur' }]
}

// 选项数据
const patientOptions = ref([])
const medicalRecordOptions = ref([])
const drugOptions = ref([])

// 当前处方详情
const currentPrescription = ref(null)

// 编辑状态
const isEdit = ref(false)

// 对话框标题
const dialogTitle = computed(() => isEdit.value ? '编辑处方' : '新建处方')

// 获取医生ID
const getDoctorId = async () => {
  try {
    const userInfo = userStore.userInfo
    if (userInfo && (userInfo.doctorId || userInfo.doctor)) {
      return userInfo.doctorId || userInfo.doctor
    }
    
    const userId = userStore.userId || userInfo?.id || userInfo?._id
    if (!userId) {
      ElMessage.error('用户未登录或无法获取用户ID')
      return null
    }

    const res = await doctorAPI.getDoctorByUserId(userId)
    if (res.success && res.data) {
      return res.data.id || res.data._id
    } else {
      ElMessage.error('获取医生信息失败')
      return null
    }
  } catch (error) {
    console.error('获取医生ID失败:', error)
    ElMessage.error('获取医生信息失败，请重新登录')
    return null
  }
}

// 获取状态标签类型
const getStatusType = (status) => {
  switch (status) {
    case '待审核':
      return 'warning'
    case '已审核':
      return 'success'
    case '已发药':
      return 'primary'
    case '已作废':
      return 'danger'
    default:
      return 'info'
  }
}

// 加载处方列表
const loadPrescriptions = async () => {
  loading.value = true
  try {
    const doctorId = await getDoctorId()
    if (!doctorId) {
      loading.value = false
      return
    }
    
    // 构建查询参数
    const params = {
      doctorId,
      page: currentPage.value,
      limit: pageSize.value,
      ...searchForm
    }
    
    // 处理日期范围
    if (dateRange.value && dateRange.value.length === 2) {
      params.startDate = dateRange.value[0]
      params.endDate = dateRange.value[1]
    }
    
    // 移除空字段
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      }
    })
    
    const res = await prescriptionAPI.getPrescriptions(params)
    if (res.success && res.data) {
      prescriptionsList.value = res.data.prescriptions || res.data.items || []
      total.value = res.data.total || 0
    } else {
      ElMessage.error('获取处方列表失败')
    }
  } catch (error) {
    console.error('加载处方列表失败:', error)
    ElMessage.error('加载处方列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索患者
const searchPatients = async (query) => {
  if (!query) return
  
  patientLoading.value = true
  try {
    const res = await patientAPI.getPatients({ name: query, limit: 20 })
    if (res.success && res.data) {
      patientOptions.value = res.data.patients || res.data.items || []
    }
  } catch (error) {
    console.error('搜索患者失败:', error)
  } finally {
    patientLoading.value = false
  }
}

// 搜索药品
const searchDrugs = async (query) => {
  if (!query) return
  
  drugLoading.value = true
  try {
    const res = await drugAPI.getDrugs({ name: query, limit: 20 })
    if (res.success && res.data) {
      drugOptions.value = res.data.drugs || res.data.items || []
    }
  } catch (error) {
    console.error('搜索药品失败:', error)
  } finally {
    drugLoading.value = false
  }
}

// 处理患者选择
const handlePatientChange = async (patientId) => {
  if (!patientId) {
    medicalRecordOptions.value = []
    return
  }
  
  try {
    // 获取患者的医疗记录
    const res = await medicalRecordAPI.getMedicalRecords({ patientId, limit: 50 })
    if (res.success && res.data) {
      medicalRecordOptions.value = res.data.records || res.data.items || []
    }
  } catch (error) {
    console.error('获取医疗记录失败:', error)
  }
}

// 处理药品选择
const handleDrugChange = (drugId, index) => {
  const drug = drugOptions.value.find(d => d.id === drugId)
  if (drug) {
    prescriptionForm.items[index].drugName = drug.name
    prescriptionForm.items[index].specification = drug.specification
  }
}

// 更新诊断列表
const updateDiagnosisList = () => {
  if (prescriptionForm.diagnosisText) {
    prescriptionForm.diagnosis = prescriptionForm.diagnosisText
      .split(';')
      .map(d => d.trim())
      .filter(d => d.length > 0)
  } else {
    prescriptionForm.diagnosis = []
  }
}

// 删除诊断
const removeDiagnosis = (index) => {
  prescriptionForm.diagnosis.splice(index, 1)
  prescriptionForm.diagnosisText = prescriptionForm.diagnosis.join('; ')
}

// 添加药品
const addMedication = () => {
  prescriptionForm.items.push({ 
    drugId: '', 
    drugName: '', 
    specification: '', 
    dosage: '', 
    quantity: 1, 
    frequency: '', 
    days: 1, 
    instructions: '' 
  })
}

// 删除药品
const removeMedication = (index) => {
  prescriptionForm.items.splice(index, 1)
}

// 重置表单
const resetForm = () => {
  prescriptionForm.patientId = ''
  prescriptionForm.medicalRecordId = ''
  prescriptionForm.type = 'western'
  prescriptionForm.diagnosisText = ''
  prescriptionForm.diagnosis = []
  prescriptionForm.items = [
    { drugId: '', drugName: '', specification: '', dosage: '', quantity: 1, frequency: '', days: 1, instructions: '' }
  ]
  prescriptionForm.remarks = ''
  
  patientOptions.value = []
  medicalRecordOptions.value = []
  drugOptions.value = []
  isEdit.value = false
}

// 显示新建处方对话框
const showCreatePrescription = () => {
  resetForm()
  prescriptionDialogVisible.value = true
}

// 编辑处方
const editPrescription = (row) => {
  resetForm()
  isEdit.value = true
  
  // 填充表单数据
  Object.assign(prescriptionForm, {
    ...row,
    diagnosisText: Array.isArray(row.diagnosis) ? row.diagnosis.join('; ') : (row.diagnosis || ''),
    diagnosis: Array.isArray(row.diagnosis) ? row.diagnosis : (row.diagnosis ? [row.diagnosis] : [])
  })
  
  // 如果有患者信息，添加到选项中
  if (row.patient || row.patientName) {
    patientOptions.value = [{
      id: row.patientId,
      name: row.patientName || row.patient?.name,
      gender: row.patient?.gender,
      age: row.patient?.age
    }]
  }
  
  prescriptionDialogVisible.value = true
}

// 查看处方详情
const viewPrescription = async (row) => {
  detailLoading.value = true
  detailDialogVisible.value = true
  
  try {
    const res = await prescriptionAPI.getPrescription(row.id || row._id)
    if (res.success && res.data) {
      currentPrescription.value = res.data
    } else {
      currentPrescription.value = row
    }
  } catch (error) {
    console.error('获取处方详情失败:', error)
    currentPrescription.value = row
  } finally {
    detailLoading.value = false
  }
}

// 审核处方
const auditPrescription = async (row) => {
  ElMessageBox.confirm('确认审核通过该处方？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await prescriptionAPI.auditPrescription(row.id || row._id, {
        auditResult: '通过',
        auditRemarks: '处方审核通过'
      })
      ElMessage.success('处方审核成功')
      loadPrescriptions()
    } catch (error) {
      console.error('处方审核失败:', error)
      ElMessage.error('处方审核失败')
    }
  }).catch(() => {})
}

// 提交处方
const submitPrescription = async () => {
  // 确保诊断列表是最新的
  updateDiagnosisList()
  
  const valid = await prescriptionFormRef.value.validate().catch(() => false)
  if (!valid) return
  
  // 验证诊断
  if (prescriptionForm.diagnosis.length === 0) {
    ElMessage.warning('请输入诊断结果')
    return
  }
  
  // 验证药品列表
  if (!prescriptionForm.items || prescriptionForm.items.length === 0) {
    ElMessage.warning('请至少添加一种药品')
    return
  }
  
  // 验证药品信息的完整性
  for (let i = 0; i < prescriptionForm.items.length; i++) {
    const item = prescriptionForm.items[i]
    if (!item.drugId || !item.dosage || !item.frequency || !item.quantity) {
      ElMessage.warning(`第${i + 1}种药品信息不完整，请填写完整`)
      return
    }
  }
  
  prescriptionLoading.value = true
  try {
    const doctorId = await getDoctorId()
    if (!doctorId) {
      throw new Error('无法获取医生信息')
    }
    
    // 准备处方数据
    const prescriptionData = {
      patientId: prescriptionForm.patientId,
      medicalRecordId: prescriptionForm.medicalRecordId,
      doctorId: doctorId,
      type: prescriptionForm.type,
      visitDate: new Date().toISOString(),
      diagnosis: prescriptionForm.diagnosis,
      items: prescriptionForm.items.filter(item => 
        item.drugId && item.dosage && item.frequency
      ).map(item => ({
        drugId: item.drugId,
        drugName: item.drugName,
        specification: item.specification,
        dosage: item.dosage,
        frequency: item.frequency,
        quantity: parseInt(item.quantity) || 1,
        days: parseInt(item.days) || 1,
        instructions: item.instructions || ''
      })),
      remarks: prescriptionForm.remarks || '',
      status: '待审核'
    }
    
    let res
    if (isEdit.value) {
      res = await prescriptionAPI.updatePrescription(currentPrescription.value.id, prescriptionData)
    } else {
      res = await prescriptionAPI.createPrescription(prescriptionData)
    }
    
    if (res.success) {
      ElMessage.success(isEdit.value ? '处方更新成功' : '处方创建成功')
      prescriptionDialogVisible.value = false
      loadPrescriptions()
    } else {
      ElMessage.error(res.message || '保存失败')
    }
  } catch (error) {
    console.error('保存处方失败:', error)
    ElMessage.error('保存处方失败：' + (error.message || '网络错误'))
  } finally {
    prescriptionLoading.value = false
  }
}

// 打印处方
const printPrescription = () => {
  if (!currentPrescription.value) return
  
  const printWindow = window.open('', '_blank')
  if (!printWindow) {
    ElMessage.warning('请允许弹出窗口以打印处方')
    return
  }
  
  const prescription = currentPrescription.value
  const printContent = `
    <html>
      <head>
        <title>处方单</title>
        <style>
          body { font-family: Arial, sans-serif; margin: 20px; }
          h1 { text-align: center; margin-bottom: 20px; }
          .header { border-bottom: 1px solid #ddd; padding-bottom: 10px; margin-bottom: 20px; }
          .info-item { margin-bottom: 10px; }
          .label { font-weight: bold; display: inline-block; width: 100px; }
          table { width: 100%; border-collapse: collapse; margin: 20px 0; }
          th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
          th { background-color: #f5f5f5; }
          .footer { margin-top: 30px; border-top: 1px solid #ddd; padding-top: 10px; }
        </style>
      </head>
      <body>
        <h1>处方单</h1>
        <div class="header">
          <div class="info-item"><span class="label">处方编号：</span>${prescription.prescriptionId || prescription.id}</div>
          <div class="info-item"><span class="label">患者姓名：</span>${prescription.patientName || prescription.patient?.name || '--'}</div>
          <div class="info-item"><span class="label">开具时间：</span>${formatDate(prescription.createTime || prescription.createdAt)}</div>
          <div class="info-item"><span class="label">开具医生：</span>${prescription.doctorName || '--'}</div>
        </div>
        
        <div class="info-item"><span class="label">诊断：</span>${Array.isArray(prescription.diagnosis) ? prescription.diagnosis.join('、') : (prescription.diagnosis || '--')}</div>
        
        <table>
          <thead>
            <tr>
              <th>序号</th>
              <th>药品名称</th>
              <th>规格</th>
              <th>剂量</th>
              <th>频次</th>
              <th>数量</th>
              <th>天数</th>
              <th>用法说明</th>
            </tr>
          </thead>
          <tbody>
            ${(prescription.items || []).map((item, index) => `
              <tr>
                <td>${index + 1}</td>
                <td>${item.drugName || '--'}</td>
                <td>${item.specification || '--'}</td>
                <td>${item.dosage || '--'}</td>
                <td>${item.frequency || '--'}</td>
                <td>${item.quantity || '--'}</td>
                <td>${item.days || '--'}</td>
                <td>${item.instructions || '--'}</td>
              </tr>
            `).join('')}
          </tbody>
        </table>
        
        ${prescription.remarks ? `<div class="info-item"><span class="label">备注：</span>${prescription.remarks}</div>` : ''}
        
        <div class="footer">
          <div>医生签名：__________________</div>
          <div>日期：${new Date().toLocaleDateString()}</div>
        </div>
      </body>
    </html>
  `
  
  printWindow.document.open()
  printWindow.document.write(printContent)
  printWindow.document.close()
  
  setTimeout(() => {
    printWindow.print()
    printWindow.close()
  }, 500)
}

// 搜索处方
const handleSearch = () => {
  currentPage.value = 1
  loadPrescriptions()
}

// 重置搜索
const resetSearch = () => {
  searchFormRef.value.resetFields()
  dateRange.value = []
  handleSearch()
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  loadPrescriptions()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadPrescriptions()
}

// 刷新数据
const refreshData = () => {
  loadPrescriptions()
}

// 页面加载时获取数据
onMounted(() => {
  loadPrescriptions()
})
</script>

<style scoped>
.doctor-prescription {
  width: 100%;
  overflow-x: auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.filter-container {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.pagination-container {
  text-align: right;
  padding-top: 20px;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 8px;
  flex-wrap: wrap;
}

.form-section {
  margin-bottom: 30px;
}

.section-title {
  margin: 0 0 15px 0;
  font-size: 16px;
  font-weight: bold;
  color: #409eff;
  border-left: 4px solid #409eff;
  padding-left: 10px;
}

.diagnosis-tags {
  margin-top: 10px;
}

.diagnosis-tag {
  margin-right: 10px;
  margin-bottom: 5px;
}

.patient-option, .drug-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.patient-info, .drug-spec {
  color: #909399;
  font-size: 12px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.detail-card {
  border: 1px solid #ebeef5;
  border-radius: 8px;
}

.detail-card h4 {
  margin: 0;
  color: #409eff;
  font-size: 16px;
}

/* 表格样式优化 */
:deep(.el-table) {
  font-size: 14px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

:deep(.el-table__header) {
  font-weight: bold;
}

:deep(.el-table .cell) {
  padding: 8px;
}

:deep(.el-button.is-plain:not(.is-disabled):hover) {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

/* 移动端响应式 */
@media (max-width: 768px) {
  .filter-container .el-form {
    display: flex;
    flex-direction: column;
  }
  
  .filter-container .el-form-item {
    margin-right: 0;
    margin-bottom: 10px;
  }
  
  .action-buttons {
    flex-direction: column;
    align-items: center;
  }
  
  .action-buttons .el-button {
    width: 100%;
    margin-left: 0;
    margin-bottom: 5px;
  }
}
</style> 